package com.ken.work.mvc;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Enumeration;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.ken.work.mvc.entity.JumpObj;
import com.ken.work.mvc.entity.JumpType;
import com.ken.work.mvc.entity.ReflectObj;
/*
 * @author ken
 * 2017-02-16
 */
public class DispatcherServlet extends HttpServlet{
	private static final long serialVersionUID = 1L;

	private static final Logger LOG = Logger.getLogger(DispatcherServlet.class);  
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		req.setCharacterEncoding("UTF-8");  
		resp.setContentType("text/html;charset=utf-8");
		String uriStr=req.getRequestURI();
		uriStr=uriStr.substring(uriStr.indexOf("/MVCService")+11,uriStr.length());
		LOG.info("请求路径："+uriStr);	
		Map aMap=req.getParameterMap();
		Enumeration em = req.getParameterNames();
		 while (em.hasMoreElements()) {
		    String name = (String) em.nextElement();
		    String value = req.getParameter(name);
		    LOG.info(name+" "+value);	
		}
		try {
			if("".equals(uriStr))
				throw new Exception("非法的请求路径");
			ReflectObj reflectObj=SystemMapping.get(uriStr);
			if(reflectObj!=null){
				Object classObj = reflectObj.getClassUri().newInstance();
				Method setHttpServelet = reflectObj.getClassUri().getDeclaredMethod("setHttpServlet",HttpServletRequest.class,HttpServletResponse.class);
				setHttpServelet.invoke(classObj,req, resp);
				JumpObj jumpObj=(JumpObj) reflectObj.getMethod().invoke(classObj);
				if(jumpObj.getForWordType().compareTo(JumpType.DEFAULT)==0)
					req.getRequestDispatcher(jumpObj.getForWord_Url()).forward(req,resp);
				else {
					resp.getWriter().write(jumpObj.getOutHtml());
				}
			}else {
				throw new Exception("非法的请求路径");
			}
		} catch (Exception e) {
			LOG.error(e.getMessage());
			resp.sendRedirect("/mvc/error.html");
		} 
		
		
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		System.out.println("1");
		doGet(req, resp);
	}

}
